package edu.gmu.tec.notif;

import java.util.Observable;
import java.util.Observer;

import edu.gmu.tec.scout.udp.BroadcastWrapper;
import edu.gmu.tec.scout.udp.UdpCommPackage;
import edu.gmu.tec.types.FilterImpl;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.os.Parcel;
import android.util.Log;

public class NotifSvc extends Service implements Observer{

	private static final String TAG = "TeamNotifService";
	private Binder mBinder;
	private UdpCommPackage comms;
	
	public class NotifSvcBinder extends Binder
	{
		public NotifSvc getService() {
			return NotifSvc.this;
		}
	}
	
	@Override
	public void onCreate() {
		Log.i(TAG, "Notif Service onCreate");
		
		try{
			comms = new UdpCommPackage();
			comms.addObserver(this);
		}catch(Exception e){
			Log.i(TAG, "Notif UDP Comms Exception onCreate: "+e.getMessage());
			e.printStackTrace();
		}
		mBinder = new NotifSvcBinder();
	}
	
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		Log.i(TAG, "Received start id " + startId + ": " + intent);
		// We want this service to continue running until it is explicitly
		// stopped, so return sticky.
		return START_STICKY;
	}

	@Override
	public void onDestroy() {
		Log.i(TAG, "Notif Service Stopped");
	}

	@Override
	public IBinder onBind(Intent intent) {
		Log.i(TAG, "Notif Bind");
		return mBinder;
	}

	@Override
	public void update(Observable arg0, Object arg1) {
		if(arg1 instanceof BroadcastWrapper){
			BroadcastWrapper wrapper = (BroadcastWrapper) arg1;
			if(wrapper.getContent() instanceof FilterImpl){
				Intent intent = new Intent("edu.gmu.tec.RECEIVE_MESSAGE");
				Parcel parcel = Parcel.obtain();
				ParcelableBroadcastWrapper parcelWrapper = new ParcelableBroadcastWrapper(wrapper);
				parcelWrapper.writeToParcel(parcel , 0);
				
				intent.putExtra("ParcelableBroadcastWrapper", parcelWrapper);
			}
		}
		
	}

}
